package com.excilys.formation.project.repository.impl;

import java.util.SortedSet;
import java.util.TreeSet;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.excilys.formation.project.entities.Compte;
import com.excilys.formation.project.repository.CompteDAO;

/**
 * 
 * @author excilys
 * 
 */
@Repository
public class CompteDAOImpl implements CompteDAO {
    /**
     * Entity Manager injecté par Spring.
     */
    @PersistenceContext
    private EntityManager em;

    @Override
    public Compte getCompte(String numero) {

        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Compte> criteriaQuery = criteriaBuilder.createQuery(Compte.class);
        Root<Compte> root = criteriaQuery.from(Compte.class);
        criteriaQuery.where(criteriaBuilder.equal(root.get("numero"), numero));
        return em.createQuery(criteriaQuery).getSingleResult();
    }

    @Override
    public Compte getCompteById(Long id) {
        return em.find(Compte.class, id);
    }

    @Override
    public void save(Compte compte) {
        em.persist(em.merge(compte));

    }

    @SuppressWarnings("unchecked")
    @Override
    public SortedSet<Compte> getComptesByClient(long clientId) {
        Query q = em.createQuery("SELECT c FROM Compte c WHERE c.client.id = :id ");
        q.setParameter("id", clientId);
        return new TreeSet<Compte>(q.getResultList());
    }
}
